<template>
  <div class="sku-select">
    <div :class="{show: showValue}"
         class="select ellipsis"
         @click="showClick">
      {{ data.attrsText }}
      <i class="iconfont icon-angle-down"/>
    </div>
    <div :class="{show: showValue}"
         class="value">
      <template v-if="specs.length">
        <good-info-item v-for="(spec, index1) in specs"
                        :key="spec.name"
                        :label="spec.name"
                        label-margin-bottom="10px">
          <good-spec v-for="(specVal, index2) in spec.values"
                     :key="specVal.name"
                     :active="index2 === activeIndex[index1]"
                     :data="specVal"
                     @click="specClick(index1, index2)"/>
        </good-info-item>
        <div class="submit"
             @click="submitClick">
          确定
        </div>
      </template>
      <loading v-else
               height="200px"/>
    </div>
  </div>
</template>

<script lang="ts"
        setup>
import {getGoodDetail} from '@/api/good'
import GoodInfoItem from '@/components/library/GoodInfoItem.vue'
import GoodSpec from '@/components/library/GoodSpec.vue'
import Loading from '@/components/library/Loading.vue'
import message from '@/components/library/Message/index'
import {useCartStore} from '@/stores/cart'
import type {CartItem} from '@/types/cart'
import type {GoodDetail, Skus, Spec, SpecValue} from '@/types/good'
import {storeToRefs} from 'pinia'
import {computed, ref, watch} from 'vue'

let store = useCartStore()
let {eList} = storeToRefs(store)

let props = defineProps<{
  data: CartItem
}>()

let specs = ref<Spec[]>([])
let goodDetail: GoodDetail
let skus = ref<Skus[]>([])
let activeIndex = ref<number[]>([])
// ['颜色@木耳边领-姜黄']
let activeObj = computed(() => {
  let res: string[] = []
  for (let index in activeIndex.value) {
    if (activeIndex.value[index] === -1) continue
    let spec: Spec | undefined = goodDetail?.specs?.[index]
    let specValue: SpecValue | undefined = spec?.values?.[activeIndex.value[index]]
    res.push((spec?.name ?? '') + '@' + (specValue?.name ?? ''))
  }
  return res
})
let activeSku = ref<Skus>()
let activeSkuText = computed<string>((): string => {
  let res: string[] = []
  activeSku.value?.specs?.forEach(
    item => res.push(`${item.name}: ${item.valueName}`)
  )
  return res.join(' ')
})
let initActiveIndex = () => {
  activeIndex.value = []
  activeSku.value = skus.value.find(i => i.id === props.data.skuId)
  if (!activeSku) return message.error('数据错误，请删除该商品重新添加')

  activeSku.value?.specs?.forEach(item => {
    let index = specs.value.findIndex(i => i.name === item.name)
    if (index === -1) return message.error('数据错误，请删除该商品重新添加')

    let valueIndex = specs.value[index].values?.findIndex(i => i.name === item.valueName) ?? -1
    if (valueIndex === -1) return message.error('数据错误，请删除该商品重新添加')

    activeIndex.value[index] = valueIndex
  })
}

let showValue = ref<boolean>(false)
let showClick = () => {
  showValue.value = !showValue.value
}
watch<boolean>(() => showValue.value, async (v: boolean) => {
  if (!v || specs.value.length) return initActiveIndex()

  let res: any = await getGoodDetail(<string>props.data.id)
  goodDetail = <GoodDetail>res.result
  specs.value = goodDetail?.specs ?? []
  skus.value = goodDetail?.skus ?? []

  initActiveIndex()
})

// spec切换点击事件
function specClick(index1: number, index2: number): void {
  // 点击已选中则取消选中，点击未选中则选中
  if (activeIndex.value[index1] === index2)
    activeIndex.value[index1] = -1
  else
    activeIndex.value[index1] = index2

  // 找到对应商品的sku
  activeSku.value = goodDetail?.skus?.find(item =>
    item.specs?.every(item => activeObj.value.includes(`${item.name}@${item.valueName}`))
  )
}

function submitClick(): void {
  store.updateFromCart(props.data.skuId ?? '', {
    attrsText: activeSkuText.value,
    nowPrice: activeSku.value?.price,
    price: activeSku.value?.price,
    skuId: activeSku.value?.id,
    stock: activeSku.value?.inventory,
    count: props.data.count,
    selected: props.data.selected,
    isEffective: true
  })
}
</script>

<style lang="less"
       scoped>
.sku-select {
  position: relative;

  .select {
    border: 1px solid #e4e4e4;
    cursor: pointer;
    position: relative;
    height: 30px;
    padding: 0 20px 0 5px;
    color: #999999;
    min-width: 260px;
    max-width: 260px;
    font-size: 14px;
    line-height: 30px;

    &.show {
      background-color: #fff;
      border-bottom: none;
    }

    i {
      font-size: 12px;
      position: absolute;
      right: 5px;
    }
  }

  .value {
    display: none;
    border: 1px solid #e4e4e4;
    padding: 40px 20px;
    z-index: 10;
    position: absolute;
    top: 100%;
    left: 0;
    width: 400px;
    background-color: white;

    &.show {
      display: block;
    }

    .submit {
      width: 60px;
      height: 32px;
      justify-content: center;
      display: flex;
      align-items: center;
      color: white;
      background-color: @xtxColor;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 50px;
    }
  }
}
</style>